<template>
  <div class="w-full juzhong cursor-pointer" :class="[...heightclass,$props.easymodel?'border-0 border-b-2':'border rounded',
  jiaodian?$props.easymodel?'border-black':'border-blue-400 fulloutshaw':'border-gray-300']" ref="waicengref"
       @click.stop="dianjiselect">
    <!--    多选模块-->
    <div v-if="$props.multiple" class="w-full h-full flex justify-center items-center flex-col">
      <!--      上面是显示tag标签的区域-->
      <div></div>
      <!--      下面是input区域-->
      <input type="text" class="border-0 focus:ring-0 outline-none h-full w-full"
             :value="wenzi" @focus="getfocus" @blur="losefocus" ref="selectref"
             :placeholder="$props.modelValue.length>0?'':$props.placeholder">
    </div>
    <!--    单选模式-->
    <div v-else class="w-full h-full flex justify-center items-center">
      <input type="text" :value="$props.modelValue" @focus="getfocus" @blur="losefocus" ref="selectref"
             class="border-0 focus:ring-0 outline-none h-full w-full px-2 juzhong rounded"
             :class="[$props.filterable?'cursor-text':'cursor-pointer']"
             :readonly="!$props.filterable"
             :placeholder="$props.modelValue.length>0?'':$props.placeholder">
      <div class="h-full juzhong px-2">
        <Icon v-if="clearable" class="text-gray-300 hover:text-red-500 active:text-blue-500 text-xl">
          <CloseCircle></CloseCircle>
        </Icon>
        <Icon v-else class="text-xl text-black">
          <ChevronUp v-show="showtatus"></ChevronUp>
          <ChevronDown v-show="!showtatus"></ChevronDown>
        </Icon>
      </div>
    </div>
    <!--    选项-->
    <div ref="optionref"
         class="absolute max-h-32 overflow-x-hidden overflow-y-auto border border-black transform"
         v-if="showtatus" :class="[weizhi==='top'?'-translate-y-full':'']">
      <div class="w-full bg-gray-50" v-if="$props.optionList.length>0">
        <div v-for="(item,index) in $props.optionList" :key="index+'hh'" @click="ceshi()"
             class="w-full cursor-pointer hover:bg-blue-200 divide-y"
             :class="[isselect(item[$props.value])?'text-blue-600 bg-blue-300':'text-gray-500',...heightclass]">
          <div class="w-full h-full flex justify-between items-center rounded">
            <span class="h-full justify-start items-center truncate flex-1 p-2">{{ item[$props.label] }}</span>
            <span class="h-full juzhong flex-initial p-2">
                <Icon class="text-xl" v-show="isselect(item[$props.value])">
                  <Checkmark></Checkmark>
                </Icon>
            </span>
          </div>
        </div>
      </div>
      <div v-else class="w-full h-20 juzhong bg-gray-50">
        <span class="text-gray-300 text-xl">没有可选项</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, nextTick, computed, watch} from "vue";
import {Icon} from '@vicons/utils' // 外壳
import {CloseCircle} from '@vicons/ionicons5'   // 关闭
import {ChevronUp} from '@vicons/ionicons5'   // 向上箭头
import {ChevronDown} from '@vicons/ionicons5'   // 想下箭头
import {Checkmark} from '@vicons/ionicons5'   // 对号
export default defineComponent({
  name: "gselect",
  props: {
    // 简易模式
    easymodel: {
      type: Boolean,
      default: false,
    },
    // 占位文字
    placeholder: {
      type: String,
      default: "请输入",
    },
    // 尺寸
    size: {
      type: String,
      default: "middle",
      validator(value) {
        return ["large", "middle", "mini"].includes(value)
      }
    },
    // 一键清除
    clear: {
      type: Boolean,
      default: false,
    },
    // v-model
    modelValue: {
      type: String,
      default: "",
    },
    // 搜索功能
    filterable: {
      type: Boolean,
      default: false,
    },
    // 需要遍历的数组
    optionList: {
      require: true,
      type: Array,
    },
    // label
    label: {
      type: String,
      default: "label",
    },
    // value
    value: {
      type: String,
      default: "value",
    },
    // 多选
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  setup(prop, content) {
    // input元素
    const selectref = ref(null)
    // input外层的div元
    const waicengref = ref(null)
    // 展开收起箭头状态
    const showtatus = ref(false)
    // 选项标签
    const optionref = ref(null)
    // input的文字
    const wenzi = ref("")
    // 默认定位
    const weizhi = ref("bottom")
    const changecall = (e) => {
      content.emit("change", e.target.value)
    }
    // 主动获取焦点和主动失去焦点
    const focus = () => {
      nextTick(() => {
        selectref.value.focus()
      })
    }
    const blur = () => {
      nextTick(() => {
        selectref.value.blur()
      })
    }

    // 焦点状态的改变
    const jiaodian = ref(false)
    const getfocus = () => {
      jiaodian.value = true
      content.emit("focus")
    }
    const losefocus = () => {
      jiaodian.value = false
      content.emit("blur")
      showtatus.value = false
    }

    // 初始化的时候，获取高度
    const heightclass = ref([])
    const init = () => {
      switch (prop.size) {
        case "middle":
          heightclass.value = [...heightclass.value, "h-9"]
          break
        case "mini":
          heightclass.value = [...heightclass.value, "h-7"]
          break
        case "large":
          heightclass.value = [...heightclass.value, "h-10"]
          break
      }
    }

    // 清除状态
    const clearable = computed(() => {
      return prop.clear && prop.modelValue
    })
    const qingkong = () => {
      if (prop.multiple) {
        content.emit("update:modelValue", [])
      } else {
        content.emit("update:modelValue", "")
      }
      content.emit("clear")
    }
    const filterresult = computed(() => {
      if (prop.filterable) {
        const jieguo = prop.optionList.filter(item=>{
          if(prop.multiple){
            return item[prop.label].search(wenzi) !== -1
          }else{
            return item[prop.label].search(prop.modelValue) !== -1
          }
        })
        return jieguo
      } else {
        return prop.optionList || []
      }
    })
    // optionref定位
    const dingwei = () => {
      const {width, height, top, left} = waicengref.value.getBoundingClientRect()
      optionref.value.style.width = `${width}px`
      let positionvalue = {
        top: {
          top: top + window.screenY - 5,
          left: left + window.screenX
        },
        bottom: {
          top: top + height + window.scrollY + 5,
          left: left + window.scrollX
        },
      }
      const dibujuli = document.documentElement.clientHeight - top - height
      if (dibujuli < 130) {
        weizhi.value = "top"
      }
      optionref.value.style.left = `${positionvalue[weizhi.value].left}px`
      optionref.value.style.top = `${positionvalue[weizhi.value].top}px`
    }
    // 点击select框
    const dianjiselect = () => {
      showtatus.value = !showtatus.value
      if (showtatus.value) {
        nextTick(() => {
          document.body.appendChild(optionref.value)
          dingwei()
        })
      }
    }
    // 判断是不是已经被选中
    const isselect = (value) => {
      if (prop.multiple) {
        return prop.modelValue.includes(value)
      } else {
        return prop.modelValue === value
      }
    }
    // 点击一个选项
    const clickitem = (item) => {
      console.log(item, "点击事件")
      const thisvalue = item[prop.value]
      if (prop.multiple) {
        const thisindex = prop.modelValue.indexOf(thisvalue)
        if (thisindex === -1) {
          content.emit("update:modelValue", [...prop.modelValue, thisvalue])
        } else {
          content.emit("update:modelValue", prop.modelValue.slice(thisindex, 1))
        }
      } else {
        if (prop.modelValue === thisvalue) {
          content.emit("update:modelValue", "")
          content.emit("change", "")
        } else {
          content.emit("update:modelValue", thisvalue)
          content.emit("change", thisvalue)
        }
      }
    }
    // 测试函数
    const ceshi = ()=>{
      console.log("sdfsdfsdlfskld")
    }

    // 初始化区域
    init()
    return {
      changecall,
      selectref,
      focus,
      blur,
      heightclass,
      getfocus,
      losefocus,
      jiaodian,
      waicengref,
      qingkong,
      clearable,
      showtatus,
      filterresult,
      wenzi,
      dianjiselect,
      optionref,
      weizhi,
      clickitem,
      isselect,ceshi,
    }
  },
  components: {Icon, CloseCircle, ChevronUp, ChevronDown, Checkmark,},
})
</script>

<style scoped>
</style>
